<template>
  <el-form ref="custom-form" :model="formData" :label-width="labelWidth">
    <template v-for="item in fieldList" :key="item.id">
      <el-form-item :label="item.title" :prop="item.name" :rules="item.rules" :required="item.required">
        <component :is="componentMap[item.type] || componentMap.default" v-model="formData[item.name]" :config="item"
          :options="item.options" />
      </el-form-item>
    </template>
  </el-form>
</template>
<script setup lang="ts">
import { ref, useTemplateRef, toRefs, watch } from 'vue'
import { type FormInstance } from 'element-plus'
import {
  CustomFileUpload,
  CustomInput,
  CustomSelect,
  CustomUserSelect,
  CustomDefault
} from '@/components/dynamic-form-field'


const props = defineProps<{
  data?: any, // 编辑时数据
  formSchema: any[], // 表单字段配置
  labelWidth: string, // label宽度
}>()

const { data, formSchema } = toRefs(props)

const customFormRef = useTemplateRef<FormInstance>('custom-form')

const formData = ref<any>({

})

const componentMap: any = {
  file: CustomFileUpload,
  input: CustomInput,
  select: CustomSelect,
  userSelect: CustomUserSelect,
  default: CustomDefault
}

const fieldList = ref<any[]>([])

const getCustomFormData = () => {
  return new Promise((resolve, reject) => {
    customFormRef.value?.validate(async (isValid) => {
      if (isValid) {
        const obj = { ...formData.value, cfv: {} }
        for (let i in formData.value) {
          //const field = fieldList.value.find((item) => item.name === i)
          // if (field?.type === 'userSelect') {
          //   // todo
          // }
          obj.cfv[i] = obj[i]
          delete obj[i]
        }
        resolve(obj)
      } else {
        reject(new Error('表单验证未通过'))
      }
    })
  })
}

watch(() => formSchema.value, () => {
  fieldList.value = [...formSchema.value]
  fieldList.value.forEach((item) => {
    if (data.value.cfv) {
      const cfv = data.value.cfv
      formData.value[item.name] = cfv[item.name]
    } else {
      formData.value[item.name] = item.defaultValue
    }
  })
})

defineExpose({ getCustomFormData })
</script>
<style scoped></style>